#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
4399账号批量注册工具 - GUI界面
具有科技感的现代化界面
"""

import sys
import os
import tempfile
import shutil

# 导入调试日志器（正式版本关闭详细日志）
try:
    from debug_logger import debug_logger, log_info, log_error, log_exception, init_debug_logging
    DEBUG_ENABLED = False  # 正式版本关闭调试日志
    # 正式版本不初始化详细调试日志
    # init_debug_logging()
    # log_info("程序启动", version="正式版本")
except ImportError:
    DEBUG_ENABLED = False

# 简化的日志函数（正式版本）
def log_info(msg, **kwargs): pass  # 正式版本不输出日志
def log_error(msg, **kwargs): pass
def log_exception(msg, **kwargs): pass

# 在导入其他模块之前应用ddddocr修复
def apply_startup_fixes():
    """应用启动时的修复"""
    try:
        # 检查是否为打包环境
        if getattr(sys, 'frozen', False):
            # 内嵌的ddddocr修复代码
            try:
                apply_embedded_ddddocr_fix()
            except Exception as e:
                pass  # 静默处理错误

            # 尝试导入并应用修复
            try:
                from ddddocr_runtime_fix import apply_ddddocr_runtime_fix
                apply_ddddocr_runtime_fix()
            except ImportError:
                pass  # 静默处理导入错误
            except Exception as e:
                pass  # 静默处理应用错误
    except Exception as e:
        pass  # 静默处理启动错误

def apply_embedded_ddddocr_fix():
    """内嵌的ddddocr修复代码"""

    if not getattr(sys, 'frozen', False):
        return

    try:
        base_path = sys._MEIPASS

        # 搜索所有.onnx文件
        onnx_files = {}
        for root, dirs, files in os.walk(base_path):
            for file in files:
                if file.endswith('.onnx') and any(keyword in file for keyword in ['common', 'det', 'old']):
                    full_path = os.path.join(root, file)
                    size = os.path.getsize(full_path)
                    if size > 1000:  # 确保不是空文件
                        onnx_files[file] = full_path

        if not onnx_files:
            return

        # 创建临时目录
        temp_dir = tempfile.mkdtemp(prefix='ddddocr_embedded_fix_')

        # 复制模型文件
        for model_name, source_path in onnx_files.items():
            dest_path = os.path.join(temp_dir, model_name)
            shutil.copy2(source_path, dest_path)

        # 设置环境变量
        os.environ['DDDDOCR_MODEL_PATH'] = temp_dir

        # 尝试预加载ddddocr
        try:
            import ddddocr
            # 修补ddddocr的初始化方法
            if hasattr(ddddocr, 'DdddOcr'):
                original_init = ddddocr.DdddOcr.__init__

                def patched_init(self, show_ad=True, old=False, beta=False, det=False, ocr=True):
                    try:
                        return original_init(self, show_ad=show_ad, old=old, beta=beta, det=det, ocr=ocr)
                    except Exception as e:
                        if "data list is empty" in str(e).lower():
                            # 临时修改工作目录
                            old_cwd = os.getcwd()
                            try:
                                os.chdir(temp_dir)
                                return original_init(self, show_ad=show_ad, old=old, beta=beta, det=det, ocr=ocr)
                            finally:
                                os.chdir(old_cwd)
                        else:
                            raise e

                ddddocr.DdddOcr.__init__ = patched_init
        except Exception as e:
            pass  # 静默处理ddddocr预加载失败

    except Exception as e:
        pass  # 静默处理内嵌修复失败

# 应用启动修复
apply_startup_fixes()

from PySide2.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
                               QHBoxLayout, QLabel, QPushButton, QStackedWidget,
                               QFrame, QScrollArea, QTextEdit, QSpinBox, QLineEdit,
                               QComboBox, QCheckBox, QProgressBar, QTableWidget,
                               QTableWidgetItem, QHeaderView, QMessageBox, QGroupBox,
                               QFormLayout, QSplitter, QTabWidget, QProgressDialog)
from PySide2.QtCore import Qt, QTimer, QThread, Signal, QPropertyAnimation, QEasingCurve, QRect
from PySide2.QtGui import QFont, QPixmap, QPalette, QColor, QLinearGradient, QPainter, QBrush

from config import Config
from register_bot import Register4399Bot
from gui_threads import RegisterThread


class CyberButton(QPushButton):
    """科技感按钮"""
    def __init__(self, text, parent=None):
        super().__init__(text, parent)
        self.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                    stop:0 #1a1a2e, stop:1 #16213e);
                border: 2px solid #00d4ff;
                border-radius: 10px;
                color: #00d4ff;
                font-weight: bold;
                font-size: 14px;
                padding: 12px 24px;
                text-transform: uppercase;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                    stop:0 #00d4ff, stop:1 #0f3460);
                color: #ffffff;
                border: 2px solid #00ffff;
            }
            QPushButton:pressed {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                    stop:0 #0f3460, stop:1 #1a1a2e);
                border: 2px solid #ff6b6b;
            }
            QPushButton:disabled {
                background: #2a2a3e;
                border: 2px solid #555555;
                color: #888888;
            }
        """)


class CyberFrame(QFrame):
    """科技感框架"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setStyleSheet("""
            QFrame {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                    stop:0 #0f0f23, stop:1 #1a1a2e);
                border: 1px solid #00d4ff;
                border-radius: 15px;
                margin: 5px;
            }
        """)


class CyberLabel(QLabel):
    """科技感标签"""
    def __init__(self, text, parent=None):
        super().__init__(text, parent)
        self.setStyleSheet("""
            QLabel {
                color: #00d4ff;
                font-weight: bold;
                font-size: 16px;
                background: transparent;
            }
        """)


class CyberLineEdit(QLineEdit):
    """科技感输入框"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setStyleSheet("""
            QLineEdit {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                    stop:0 #1a1a2e, stop:1 #16213e);
                border: 2px solid #00d4ff;
                border-radius: 8px;
                color: #ffffff;
                font-size: 14px;
                padding: 8px 12px;
            }
            QLineEdit:focus {
                border: 2px solid #00ffff;
            }
        """)


class CyberTextEdit(QTextEdit):
    """科技感文本编辑器"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setStyleSheet("""
            QTextEdit {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                    stop:0 #0f0f23, stop:1 #1a1a2e);
                border: 2px solid #00d4ff;
                border-radius: 8px;
                color: #ffffff;
                font-family: 'Consolas', 'Monaco', monospace;
                font-size: 12px;
                padding: 8px;
            }
            QScrollBar:vertical {
                background: #1a1a2e;
                width: 12px;
                border-radius: 6px;
            }
            QScrollBar::handle:vertical {
                background: #00d4ff;
                border-radius: 6px;
                min-height: 20px;
            }
            QScrollBar::handle:vertical:hover {
                background: #00ffff;
            }
        """)


class CyberProgressBar(QProgressBar):
    """科技感进度条"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setStyleSheet("""
            QProgressBar {
                background: #1a1a2e;
                border: 2px solid #00d4ff;
                border-radius: 10px;
                text-align: center;
                color: #ffffff;
                font-weight: bold;
            }
            QProgressBar::chunk {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00d4ff, stop:1 #00ffff);
                border-radius: 8px;
            }
        """)


class MainWindow(QMainWindow):
    """主窗口"""
    def __init__(self):
        super().__init__()
        self.config = Config()
        self.register_thread = None
        self.init_ui()
        self.setup_style()
        
    def init_ui(self):
        """初始化UI"""
        self.setWindowTitle("4399账号批量注册工具 - 科技版")
        self.setGeometry(100, 100, 1400, 900)
        
        # 创建中央部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 主布局
        main_layout = QHBoxLayout(central_widget)
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)
        
        # 创建侧边栏
        self.create_sidebar(main_layout)
        
        # 创建主内容区域
        self.create_main_content(main_layout)
        
    def create_sidebar(self, main_layout):
        """创建侧边栏"""
        sidebar = CyberFrame()
        sidebar.setFixedWidth(250)
        sidebar_layout = QVBoxLayout(sidebar)
        
        # 标题
        title_label = QLabel("4399工具")
        title_label.setStyleSheet("""
            QLabel {
                color: #00ffff;
                font-size: 24px;
                font-weight: bold;
                text-align: center;
                padding: 20px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                    stop:0 #ff6b6b, stop:1 #00d4ff);
                -webkit-background-clip: text;
                border-radius: 10px;
                margin-bottom: 20px;
            }
        """)
        title_label.setAlignment(Qt.AlignCenter)
        sidebar_layout.addWidget(title_label)
        
        # 导航按钮
        self.nav_buttons = []
        nav_items = [
            ("🏠 主页", "home"),
            ("⚙️ 配置", "config"),
            ("📝 注册", "register"),
            ("👥 账号管理", "accounts"),
            ("📊 统计", "stats")
        ]
        
        for text, page in nav_items:
            btn = CyberButton(text)
            # 修复lambda函数问题
            btn.clicked.connect(lambda checked=False, p=page: self.switch_page(p))
            self.nav_buttons.append(btn)
            sidebar_layout.addWidget(btn)
        
        sidebar_layout.addStretch()
        main_layout.addWidget(sidebar)
        
    def create_main_content(self, main_layout):
        """创建主内容区域"""
        # 主内容区域
        content_frame = CyberFrame()
        content_layout = QVBoxLayout(content_frame)
        
        # 页面堆栈
        self.stacked_widget = QStackedWidget()
        content_layout.addWidget(self.stacked_widget)
        
        # 创建各个页面
        self.create_pages()
        
        main_layout.addWidget(content_frame, 1)
        
    def create_pages(self):
        """创建各个页面"""
        # 主页
        self.home_page = self.create_home_page()
        self.stacked_widget.addWidget(self.home_page)
        
        # 配置页面
        self.config_page = self.create_config_page()
        self.stacked_widget.addWidget(self.config_page)
        
        # 注册页面
        self.register_page = self.create_register_page()
        self.stacked_widget.addWidget(self.register_page)

        # 账号管理页面
        self.accounts_page = self.create_accounts_page()
        self.stacked_widget.addWidget(self.accounts_page)

        # 统计页面
        self.stats_page = self.create_stats_page()
        self.stacked_widget.addWidget(self.stats_page)
        
    def create_home_page(self):
        """创建主页"""
        page = QWidget()
        layout = QVBoxLayout(page)
        
        # 欢迎标题
        welcome_label = QLabel("欢迎使用4399账号批量注册工具")
        welcome_label.setStyleSheet("""
            QLabel {
                color: #00ffff;
                font-size: 32px;
                font-weight: bold;
                text-align: center;
                padding: 40px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                    stop:0 rgba(255, 107, 107, 0.3), stop:1 rgba(0, 212, 255, 0.3));
                border-radius: 15px;
                margin: 20px;
            }
        """)
        welcome_label.setAlignment(Qt.AlignCenter)
        layout.addWidget(welcome_label)
        
        # 功能介绍
        features_frame = CyberFrame()
        features_layout = QVBoxLayout(features_frame)
        
        features_title = CyberLabel("主要功能")
        features_title.setAlignment(Qt.AlignCenter)
        features_layout.addWidget(features_title)
        
        features_text = """
        🚀 批量注册4399账号
        ⚙️ 智能配置管理
        📊 实时进度监控
        🛡️ 验证码自动识别
        💾 账号数据管理
        🔧 多线程并行处理
        """
        
        features_label = QLabel(features_text)
        features_label.setStyleSheet("""
            QLabel {
                color: #ffffff;
                font-size: 16px;
                line-height: 1.8;
                padding: 20px;
                background: transparent;
            }
        """)
        features_layout.addWidget(features_label)
        
        layout.addWidget(features_frame)
        layout.addStretch()
        
        return page

    def create_config_page(self):
        """创建配置页面"""
        page = QWidget()
        layout = QVBoxLayout(page)

        # 页面标题
        title = CyberLabel("配置设置")
        title.setAlignment(Qt.AlignCenter)
        title.setStyleSheet("font-size: 24px; margin: 20px;")
        layout.addWidget(title)

        # 配置表单
        config_frame = CyberFrame()
        config_layout = QFormLayout(config_frame)

        # 身份信息（每次启动都需要重新输入，不保存敏感信息）
        self.real_name_edit = CyberLineEdit()
        self.real_name_edit.setPlaceholderText("请输入真实姓名（每次启动需重新输入）")
        config_layout.addRow(CyberLabel("真实姓名:"), self.real_name_edit)

        self.id_card_edit = CyberLineEdit()
        self.id_card_edit.setPlaceholderText("请输入身份证号（每次启动需重新输入）")
        config_layout.addRow(CyberLabel("身份证号:"), self.id_card_edit)

        self.password_edit = CyberLineEdit()
        self.password_edit.setText(self.config.DEFAULT_PASSWORD)
        config_layout.addRow(CyberLabel("默认密码:"), self.password_edit)

        # 浏览器设置
        self.headless_checkbox = QCheckBox("无头模式")
        self.headless_checkbox.setChecked(self.config.BROWSER_CONFIG['headless'])
        self.headless_checkbox.setStyleSheet("""
            QCheckBox {
                color: #ffffff;
                font-size: 14px;
            }
            QCheckBox::indicator {
                width: 18px;
                height: 18px;
                border: 2px solid #00d4ff;
                border-radius: 3px;
                background: #1a1a2e;
            }
            QCheckBox::indicator:checked {
                background: #00d4ff;
            }
        """)
        config_layout.addRow(CyberLabel("浏览器设置:"), self.headless_checkbox)

        # 保存按钮
        save_btn = CyberButton("保存配置")
        save_btn.clicked.connect(self.save_config)
        config_layout.addRow("", save_btn)

        layout.addWidget(config_frame)
        layout.addStretch()

        return page

    def create_register_page(self):
        """创建注册页面"""
        page = QWidget()
        layout = QVBoxLayout(page)

        # 页面标题
        title = CyberLabel("批量注册账号")
        title.setAlignment(Qt.AlignCenter)
        title.setStyleSheet("font-size: 24px; margin: 20px;")
        layout.addWidget(title)

        # 注册设置
        settings_frame = CyberFrame()
        settings_layout = QFormLayout(settings_frame)

        # 注册数量
        self.register_count_spin = QSpinBox()
        self.register_count_spin.setMinimum(1)
        self.register_count_spin.setMaximum(100)
        self.register_count_spin.setValue(5)
        self.register_count_spin.setStyleSheet("""
            QSpinBox {
                background: #1a1a2e;
                border: 2px solid #00d4ff;
                border-radius: 8px;
                color: #ffffff;
                font-size: 14px;
                padding: 8px;
            }
        """)
        settings_layout.addRow(CyberLabel("注册数量:"), self.register_count_spin)

        # 账号名前缀配置
        self.username_prefix_input = QLineEdit()
        self.username_prefix_input.setText("dai")  # 默认前缀
        self.username_prefix_input.setPlaceholderText("输入账号名前缀，如：dai、user、test等")
        self.username_prefix_input.setStyleSheet("""
            QLineEdit {
                background: #1a1a2e;
                border: 2px solid #00d4ff;
                border-radius: 8px;
                color: #ffffff;
                font-size: 14px;
                padding: 8px;
            }
            QLineEdit:focus {
                border-color: #00ffff;
            }
        """)
        settings_layout.addRow(CyberLabel("账号名前缀:"), self.username_prefix_input)

        # UUID随机位数配置
        self.uuid_length_spin = QSpinBox()
        self.uuid_length_spin.setMinimum(4)
        self.uuid_length_spin.setMaximum(20)
        self.uuid_length_spin.setValue(10)  # 默认10位
        self.uuid_length_spin.setStyleSheet("""
            QSpinBox {
                background: #1a1a2e;
                border: 2px solid #00d4ff;
                border-radius: 8px;
                color: #ffffff;
                font-size: 14px;
                padding: 8px;
            }
        """)
        settings_layout.addRow(CyberLabel("随机数位数:"), self.uuid_length_spin)

        # 线程数配置
        self.register_threads_spin = QSpinBox()
        self.register_threads_spin.setMinimum(1)
        self.register_threads_spin.setMaximum(16)
        self.register_threads_spin.setValue(8)
        self.register_threads_spin.setStyleSheet("""
            QSpinBox {
                background: #1a1a2e;
                border: 2px solid #00d4ff;
                border-radius: 8px;
                color: #ffffff;
                font-size: 14px;
                padding: 8px;
            }
        """)
        settings_layout.addRow(CyberLabel("并发线程数:"), self.register_threads_spin)

        # 开始注册按钮
        self.start_register_btn = CyberButton("开始注册")
        self.start_register_btn.clicked.connect(self.toggle_registration)
        settings_layout.addRow("", self.start_register_btn)

        # 注册状态标记
        self.is_registering = False
        self.register_thread = None

        layout.addWidget(settings_frame)

        # 进度显示
        progress_frame = CyberFrame()
        progress_layout = QVBoxLayout(progress_frame)

        progress_title = CyberLabel("注册进度")
        progress_layout.addWidget(progress_title)

        self.register_progress = CyberProgressBar()
        progress_layout.addWidget(self.register_progress)

        # 日志显示
        self.register_log = CyberTextEdit()
        self.register_log.setMaximumHeight(200)
        progress_layout.addWidget(self.register_log)

        layout.addWidget(progress_frame)

        return page



    def create_accounts_page(self):
        """创建账号管理页面"""
        page = QWidget()
        layout = QVBoxLayout(page)

        # 页面标题
        title = CyberLabel("账号管理")
        title.setAlignment(Qt.AlignCenter)
        title.setStyleSheet("font-size: 24px; margin: 20px;")
        layout.addWidget(title)

        # 操作提示
        tip_label = QLabel("💡 操作提示：点击选择行，Ctrl+点击多选，Shift+点击连续选择")
        tip_label.setStyleSheet("""
            QLabel {
                color: #00d4ff;
                font-size: 12px;
                padding: 5px;
                background: rgba(0, 212, 255, 0.1);
                border: 1px solid #00d4ff;
                border-radius: 4px;
                margin: 5px;
            }
        """)
        layout.addWidget(tip_label)

        # 账号表格
        self.accounts_table = QTableWidget()
        self.accounts_table.setColumnCount(4)
        self.accounts_table.setHorizontalHeaderLabels(["序号", "用户名", "密码", "状态"])
        # 设置列宽
        self.accounts_table.setColumnWidth(0, 60)  # 序号列较窄
        self.accounts_table.horizontalHeader().setStretchLastSection(True)
        # 隐藏左侧默认行号列
        self.accounts_table.verticalHeader().setVisible(False)
        # 启用多选 - 支持Ctrl和Shift多选
        self.accounts_table.setSelectionBehavior(QTableWidget.SelectRows)
        self.accounts_table.setSelectionMode(QTableWidget.ExtendedSelection)
        self.accounts_table.setStyleSheet("""
            QTableWidget {
                background: #1a1a2e;
                border: 2px solid #00d4ff;
                border-radius: 8px;
                color: #ffffff;
                gridline-color: #00d4ff;
            }
            QTableWidget::item {
                padding: 8px;
                border-bottom: 1px solid #00d4ff;
            }
            QTableWidget::item:selected {
                background: #00d4ff;
                color: #000000;
            }
            QHeaderView::section {
                background: #0f3460;
                color: #00ffff;
                padding: 8px;
                border: 1px solid #00d4ff;
                font-weight: bold;
            }
        """)
        layout.addWidget(self.accounts_table)

        # 操作按钮
        buttons_layout = QHBoxLayout()

        refresh_btn = CyberButton("刷新")
        refresh_btn.clicked.connect(self.refresh_accounts)
        buttons_layout.addWidget(refresh_btn)

        export_btn = CyberButton("导出")
        export_btn.clicked.connect(self.export_accounts)
        buttons_layout.addWidget(export_btn)

        delete_btn = CyberButton("删除选中")
        delete_btn.clicked.connect(self.delete_selected_accounts)
        buttons_layout.addWidget(delete_btn)

        clear_btn = CyberButton("清空全部")
        clear_btn.clicked.connect(self.clear_accounts)
        buttons_layout.addWidget(clear_btn)

        reset_used_btn = CyberButton("重置已使用")
        reset_used_btn.clicked.connect(self.reset_used_accounts)
        buttons_layout.addWidget(reset_used_btn)

        buttons_layout.addStretch()
        layout.addLayout(buttons_layout)

        return page

    def create_stats_page(self):
        """创建统计页面"""
        page = QWidget()
        layout = QVBoxLayout(page)

        # 页面标题
        title = CyberLabel("统计信息")
        title.setAlignment(Qt.AlignCenter)
        title.setStyleSheet("font-size: 24px; margin: 20px;")
        layout.addWidget(title)

        # 统计卡片
        stats_layout = QHBoxLayout()

        # 注册统计
        self.register_stats_card = self.create_stat_card("已注册账号", "0", "#ff6b6b")
        stats_layout.addWidget(self.register_stats_card)

        # # 投票统计
        # self.vote_stats_card = self.create_stat_card("投票次数", "0", "#00d4ff")
        # stats_layout.addWidget(self.vote_stats_card)

        # 成功率统计
        self.success_stats_card = self.create_stat_card("成功率", "0%", "#4ecdc4")
        stats_layout.addWidget(self.success_stats_card)

        layout.addLayout(stats_layout)

        # 刷新按钮
        refresh_btn = CyberButton("刷新统计")
        refresh_btn.clicked.connect(self.refresh_stats)
        layout.addWidget(refresh_btn)

        layout.addStretch()

        return page

    def create_stat_card(self, title, value, color):
        """创建统计卡片"""
        card = CyberFrame()
        card.setFixedHeight(150)
        card_layout = QVBoxLayout(card)

        title_label = QLabel(title)
        title_label.setAlignment(Qt.AlignCenter)
        title_label.setStyleSheet(f"""
            QLabel {{
                color: {color};
                font-size: 16px;
                font-weight: bold;
                margin-bottom: 10px;
            }}
        """)
        card_layout.addWidget(title_label)

        value_label = QLabel(value)
        value_label.setAlignment(Qt.AlignCenter)
        value_label.setStyleSheet(f"""
            QLabel {{
                color: {color};
                font-size: 36px;
                font-weight: bold;
            }}
        """)
        card_layout.addWidget(value_label)

        return card

    def setup_style(self):
        """设置整体样式"""
        self.setStyleSheet("""
            QMainWindow {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                    stop:0 #0f0f23, stop:1 #1a1a2e);
            }
            QWidget {
                background: transparent;
            }
        """)

    def switch_page(self, page_name):
        """切换页面"""
        page_map = {
            "home": 0,
            "config": 1,
            "register": 2,
            "accounts": 3,
            "stats": 4
        }

        if page_name in page_map:
            self.stacked_widget.setCurrentIndex(page_map[page_name])

            # 刷新页面数据
            if page_name == "accounts":
                self.refresh_accounts()
            elif page_name == "stats":
                self.refresh_stats()

    def check_and_create_accounts_file(self):
        """检查并创建accounts.txt文件"""
        try:
            # 获取exe所在目录，确保accounts.txt在exe同目录下
            if hasattr(sys, '_MEIPASS'):
                exe_dir = os.path.dirname(sys.executable)
            else:
                exe_dir = os.path.dirname(os.path.abspath(__file__))

            accounts_file = os.path.join(exe_dir, "accounts.txt")

            if not os.path.exists(accounts_file):
                # 创建accounts.txt文件
                with open(accounts_file, 'w', encoding='utf-8') as f:
                    f.write("# 4399账号列表\n")
                    f.write("# 格式：用户名\t密码\n")
                    f.write("# 已使用的账号会被标记为 [已使用]\n")
                    f.write("\n")

                self.register_log.append("✅ 已创建 accounts.txt 文件")
            else:
                self.register_log.append("✅ accounts.txt 文件已存在")

        except Exception as e:
            error_msg = f"创建 accounts.txt 文件时出错: {str(e)}"
            self.register_log.append(f"❌ {error_msg}")
            QMessageBox.warning(self, "警告", error_msg)

    def save_config(self):
        """保存配置（不保存敏感信息）"""
        try:
            password = self.password_edit.text().strip()
            headless = self.headless_checkbox.isChecked()

            if not password:
                QMessageBox.warning(self, "警告", "请填写默认密码")
                return

            # 保存配置（仅保存密码和浏览器配置，不保存身份证和姓名）
            browser_config = {"headless": headless}
            success = self.config.save_user_config(
                password=password,
                browser_config=browser_config
            )

            if success:
                QMessageBox.information(self, "成功", "配置保存成功！\n\n注意：身份证和姓名信息不会被保存，每次使用时需要重新输入以保护您的隐私。")
            else:
                QMessageBox.critical(self, "错误", "配置保存失败！")

        except Exception as e:
            QMessageBox.critical(self, "错误", f"保存配置时出错: {str(e)}")



    def toggle_registration(self):
        """切换注册状态（开始/停止）"""
        try:
            if not self.is_registering:
                # 开始注册
                self.start_registration()
            else:
                # 停止注册
                self.stop_registration()
        except Exception as e:
            QMessageBox.critical(self, "错误", f"切换注册状态时出错: {str(e)}")
            self.reset_register_button()

    def start_registration(self):
        """开始注册"""
        try:
            # 检查身份信息是否已填写
            real_name = self.real_name_edit.text().strip()
            id_card = self.id_card_edit.text().strip()

            if not real_name or not id_card:
                QMessageBox.warning(self, "警告", "请先在配置页面填写真实姓名和身份证号！\n\n为保护您的隐私，这些信息不会被保存，每次启动都需要重新输入。")
                # 自动切换到配置页面
                self.switch_page("config")
                return

            count = self.register_count_spin.value()

            # 创建带样式的确认对话框
            msg_box = QMessageBox(self)
            msg_box.setWindowTitle("确认")
            msg_box.setText(f"即将注册 {count} 个账号，确认继续吗？")
            msg_box.setIcon(QMessageBox.Question)
            msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)

            # 手动设置按钮文字
            yes_button = msg_box.button(QMessageBox.Yes)
            no_button = msg_box.button(QMessageBox.No)
            yes_button.setText("确认")
            no_button.setText("取消")

            # 设置亮黄色样式
            msg_box.setStyleSheet("""
                QMessageBox {
                    background-color: #000000;
                    color: #ffff00;
                    border: 3px solid #ffff00;
                    border-radius: 10px;
                    font-size: 16px;
                    font-weight: bold;
                }
                QMessageBox QLabel {
                    color: #ffff00;
                    font-size: 16px;
                    font-weight: bold;
                    background-color: #000000;
                    padding: 20px;
                    border: none;
                }
                QMessageBox QPushButton {
                    background-color: #ffff00;
                    color: #000000;
                    border: 2px solid #ffff00;
                    border-radius: 8px;
                    padding: 10px 20px;
                    font-weight: bold;
                    font-size: 16px;
                    min-width: 100px;
                    min-height: 35px;
                    margin: 5px;
                }
                QMessageBox QPushButton:hover {
                    background-color: #ffffff;
                    color: #000000;
                    border: 2px solid #ffff00;
                }
            """)

            reply = msg_box.exec_()

            if reply == QMessageBox.Yes:
                # 检查并创建accounts.txt文件
                self.check_and_create_accounts_file()

                # 更新按钮状态
                self.is_registering = True
                self.start_register_btn.setText("停止注册")
                self.start_register_btn.setStyleSheet("""
                    QPushButton {
                        background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                                                  stop:0 #ff4444, stop:1 #cc0000);
                        color: white;
                        border: 2px solid #ff6666;
                        border-radius: 8px;
                        padding: 8px 16px;
                        font-weight: bold;
                        font-size: 14px;
                    }
                    QPushButton:hover {
                        background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                                                  stop:0 #ff6666, stop:1 #ff0000);
                        border: 2px solid #ff8888;
                    }
                """)

                self.register_progress.setValue(0)
                self.register_log.clear()
                self.register_log.append(f"开始注册 {count} 个账号...")

                # 获取用户配置
                max_workers = self.register_threads_spin.value()
                username_prefix = self.username_prefix_input.text().strip() or "dai"  # 如果为空则使用默认值
                uuid_length = self.uuid_length_spin.value()

                # 启动注册线程，传递所有配置参数
                self.register_thread = RegisterThread(count, real_name, id_card, max_workers, username_prefix, uuid_length)

                # 连接信号
                self.register_thread.progress_updated.connect(self.register_progress.setValue)
                self.register_thread.log_updated.connect(self.register_log.append)
                self.register_thread.account_registered.connect(self.on_account_registered)
                self.register_thread.registration_complete.connect(self.on_registration_complete)

                # 启动线程
                self.register_thread.start()

        except Exception as e:
            QMessageBox.critical(self, "错误", f"启动注册时出错: {str(e)}")
            self.reset_register_button()

    def stop_registration(self):
        """停止注册"""
        try:
            if self.register_thread and self.register_thread.isRunning():
                self.register_log.append("🛑 正在停止注册...")

                # 调用线程的stop方法来正确停止线程池
                self.register_thread.stop()

                # 等待线程结束（最多等待5秒）
                if self.register_thread.wait(5000):
                    self.register_log.append("✅ 注册已停止")
                else:
                    self.register_log.append("⚠️ 强制终止注册线程")
                    self.register_thread.terminate()

            self.reset_register_button()

        except Exception as e:
            QMessageBox.critical(self, "错误", f"停止注册时出错: {str(e)}")
            self.reset_register_button()

    def reset_register_button(self):
        """重置注册按钮状态"""
        self.is_registering = False
        self.start_register_btn.setText("开始注册")
        # 恢复默认的CyberButton样式
        self.start_register_btn.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                                          stop:0 #00d4ff, stop:1 #0099cc);
                color: white;
                border: 2px solid #00ffff;
                border-radius: 8px;
                padding: 8px 16px;
                font-weight: bold;
                font-size: 14px;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                                          stop:0 #00ffff, stop:1 #00d4ff);
                border: 2px solid #66ffff;
            }
            QPushButton:pressed {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                                          stop:0 #0099cc, stop:1 #006699);
            }
        """)





    def refresh_accounts(self):
        """刷新账号列表"""
        try:
            self.accounts_table.setRowCount(0)

            # 获取当前工作目录和exe目录
            current_dir = os.getcwd()
            if hasattr(sys, '_MEIPASS'):
                exe_dir = os.path.dirname(sys.executable)
            else:
                exe_dir = os.path.dirname(os.path.abspath(__file__))

            # 尝试多个可能的accounts.txt位置
            possible_paths = [
                'accounts.txt',  # 当前工作目录
                os.path.join(current_dir, 'accounts.txt'),  # 明确的当前目录
                os.path.join(exe_dir, 'accounts.txt'),  # exe所在目录
            ]

            accounts_file = None
            for path in possible_paths:
                if os.path.exists(path):
                    accounts_file = path
                    break

            if not accounts_file:
                return

            if os.path.exists(accounts_file):
                with open(accounts_file, 'r', encoding='utf-8') as f:
                    lines = f.readlines()

                row_count = 0
                for line in lines:
                    line = line.strip()
                    if line:
                        # 检查是否已标记为已使用（格式：[已使用] username password）
                        if line.startswith('[已使用]'):
                            # 解析已使用账号
                            try:
                                # 去掉[已使用]前缀
                                clean_line = line.replace('[已使用]', '').strip()
                                # 去掉时间注释部分
                                if '#' in clean_line:
                                    clean_line = clean_line.split('#')[0].strip()

                                parts = clean_line.split('\t')
                                if len(parts) >= 2:
                                    username = parts[0].strip()
                                    password = parts[1].strip()
                                    status = "已使用"

                                    self.accounts_table.insertRow(row_count)
                                    self.accounts_table.setItem(row_count, 0, QTableWidgetItem(str(row_count + 1)))  # 序号
                                    self.accounts_table.setItem(row_count, 1, QTableWidgetItem(username))
                                    self.accounts_table.setItem(row_count, 2, QTableWidgetItem(password))
                                    self.accounts_table.setItem(row_count, 3, QTableWidgetItem(status))
                                    row_count += 1
                            except:
                                continue
                        else:
                            # 解析普通账号
                            parts = line.split('\t')
                            if len(parts) >= 2:
                                username = parts[0]
                                password = parts[1]
                                # 检查旧格式的已使用标记
                                status = "已使用" if len(parts) > 2 and "已使用" in parts[2] else "未使用"

                                self.accounts_table.insertRow(row_count)
                                self.accounts_table.setItem(row_count, 0, QTableWidgetItem(str(row_count + 1)))  # 序号
                                self.accounts_table.setItem(row_count, 1, QTableWidgetItem(username))
                                self.accounts_table.setItem(row_count, 2, QTableWidgetItem(password))
                                self.accounts_table.setItem(row_count, 3, QTableWidgetItem(status))
                                row_count += 1

        except Exception as e:
            QMessageBox.critical(self, "错误", f"刷新账号列表时出错: {str(e)}")

    def export_accounts(self):
        """导出账号"""
        try:
            if os.path.exists('accounts.txt'):
                QMessageBox.information(self, "提示", "账号已保存在 accounts.txt 文件中")
            else:
                QMessageBox.warning(self, "警告", "暂无账号数据")
        except Exception as e:
            QMessageBox.critical(self, "错误", f"导出账号时出错: {str(e)}")

    def refresh_stats(self):
        """刷新统计信息"""
        try:
            total_accounts = 0
            used_accounts = 0

            if os.path.exists('accounts.txt'):
                with open('accounts.txt', 'r', encoding='utf-8') as f:
                    lines = f.readlines()

                for line in lines:
                    line = line.strip()
                    if not line or line.startswith('#'):
                        continue

                    if '\t' in line:
                        total_accounts += 1
                        if line.startswith('[已使用]'):
                            used_accounts += 1

            # 计算成功率
            success_rate = 0
            if total_accounts > 0:
                success_rate = (used_accounts / total_accounts) * 100

            # 更新统计卡片
            self.update_stat_card(self.register_stats_card, str(total_accounts))
            # 投票统计已移除
            self.update_stat_card(self.success_stats_card, f"{success_rate:.1f}%")

        except Exception as e:
            pass  # 静默处理刷新统计信息失败

    def update_stat_card(self, card, new_value):
        """更新统计卡片的值"""
        try:
            # 获取卡片中的值标签（第二个子控件）
            layout = card.layout()
            if layout and layout.count() >= 2:
                value_label = layout.itemAt(1).widget()
                if value_label:
                    value_label.setText(new_value)
        except Exception as e:
            pass  # 静默处理更新统计卡片失败

    def delete_selected_accounts(self):
        """删除选中的账号"""
        try:
            # 获取选中的行
            selected_rows = set()
            selection_model = self.accounts_table.selectionModel()
            if selection_model:
                selected_indexes = selection_model.selectedRows()
                for index in selected_indexes:
                    selected_rows.add(index.row())

            if not selected_rows:
                QMessageBox.warning(self, "警告", "请先选择要删除的账号\n\n提示：\n- 点击行号选择单行\n- 按住Ctrl点击可多选\n- 按住Shift点击可连续选择")
                return

            # 确认删除
            reply = QMessageBox.question(
                self, "确认",
                f"确认要删除选中的 {len(selected_rows)} 个账号吗？此操作不可恢复！",
                QMessageBox.Yes | QMessageBox.No
            )

            if reply == QMessageBox.Yes:
                # 获取要删除的账号信息
                accounts_to_delete = []
                for row in selected_rows:
                    username_item = self.accounts_table.item(row, 1)  # 用户名在第1列
                    password_item = self.accounts_table.item(row, 2)  # 密码在第2列
                    if username_item and password_item:
                        accounts_to_delete.append((username_item.text(), password_item.text()))

                # 从文件中删除账号
                self.remove_accounts_from_file(accounts_to_delete)

                # 刷新表格
                self.refresh_accounts()

                QMessageBox.information(self, "成功", f"已删除 {len(selected_rows)} 个账号")

        except Exception as e:
            QMessageBox.critical(self, "错误", f"删除账号时出错: {str(e)}")

    def remove_accounts_from_file(self, accounts_to_delete):
        """从accounts.txt文件中删除指定账号"""
        try:
            if not os.path.exists('accounts.txt'):
                return

            # 读取所有行
            with open('accounts.txt', 'r', encoding='utf-8') as f:
                lines = f.readlines()

            # 过滤掉要删除的账号
            new_lines = []
            for line in lines:
                line_stripped = line.strip()
                if not line_stripped or line_stripped.startswith('#'):
                    new_lines.append(line)
                    continue

                should_keep = True
                for username, password in accounts_to_delete:
                    # 检查新格式 [已使用]username	password
                    if line_stripped.startswith('[已使用]'):
                        parts = line_stripped[5:].split('\t')  # 去掉[已使用]前缀
                        if len(parts) >= 2 and parts[0].strip() == username and parts[1].strip() == password:
                            should_keep = False
                            break
                    else:
                        # 检查普通格式 username	password
                        parts = line_stripped.split('\t')
                        if len(parts) >= 2 and parts[0].strip() == username and parts[1].strip() == password:
                            should_keep = False
                            break

                if should_keep:
                    new_lines.append(line)

            # 写回文件
            with open('accounts.txt', 'w', encoding='utf-8') as f:
                f.writelines(new_lines)

        except Exception as e:
            raise Exception(f"从文件删除账号失败: {str(e)}")

    def clear_accounts(self):
        """清空账号"""
        try:
            reply = QMessageBox.question(
                self, "确认",
                "确认要清空所有账号数据吗？此操作不可恢复！",
                QMessageBox.Yes | QMessageBox.No
            )

            if reply == QMessageBox.Yes:
                if os.path.exists('accounts.txt'):
                    os.remove('accounts.txt')
                self.refresh_accounts()
                QMessageBox.information(self, "成功", "账号数据已清空")

        except Exception as e:
            QMessageBox.critical(self, "错误", f"清空账号时出错: {str(e)}")

    def reset_used_accounts(self):
        """重置已使用的账号"""
        try:
            if not os.path.exists('accounts.txt'):
                QMessageBox.information(self, "提示", "账号文件不存在")
                return

            # 读取当前账号文件
            with open('accounts.txt', 'r', encoding='utf-8') as f:
                lines = f.readlines()

            # 统计已使用账号数量
            used_count = 0
            updated_lines = []

            for line in lines:
                line_stripped = line.strip()
                if line_stripped.startswith('[已使用]'):
                    # 移除[已使用]标记，恢复原始格式
                    original_line = line_stripped.replace('[已使用]', '').strip()
                    updated_lines.append(original_line + '\n')
                    used_count += 1
                else:
                    updated_lines.append(line)

            if used_count == 0:
                QMessageBox.information(self, "提示", "没有找到已使用的账号")
                return

            # 确认操作
            reply = QMessageBox.question(
                self, "确认",
                f"找到 {used_count} 个已使用的账号，确认要重置它们吗？",
                QMessageBox.Yes | QMessageBox.No
            )

            if reply == QMessageBox.Yes:
                # 写回文件
                with open('accounts.txt', 'w', encoding='utf-8') as f:
                    f.writelines(updated_lines)

                # 刷新账号列表
                self.refresh_accounts()
                QMessageBox.information(self, "成功", f"已重置 {used_count} 个账号的使用状态")

        except Exception as e:
            QMessageBox.critical(self, "错误", f"重置账号状态时出错: {str(e)}")

    def on_account_registered(self, username, password):
        """账号注册成功回调"""
        try:
            # 注意：不在这里保存账号，因为register_bot.py已经保存了
            # 避免重复保存导致accounts.txt中出现重复记录

            # 更新账号列表
            if self.stacked_widget.currentIndex() == 4:  # 账号管理页面
                self.refresh_accounts()

        except Exception as e:
            self.register_log.append(f"❌ 更新账号列表时出错: {str(e)}")

    def on_registration_complete(self, success, message):
        """注册完成回调"""
        self.reset_register_button()

        if success:
            QMessageBox.information(self, "成功", "账号注册完成！")
        else:
            QMessageBox.warning(self, "警告", f"注册过程中断: {message}")




def main():
    """主函数"""
    app = QApplication(sys.argv)

    # 设置应用程序样式
    app.setStyle('Fusion')

    # 设置全局样式，包括 QMessageBox
    app.setStyleSheet("""
        QMessageBox {
            background-color: #000000;
            color: #00ffff;
            border: 3px solid #00ffff;
            border-radius: 10px;
            min-width: 400px;
            min-height: 200px;
        }
        QMessageBox QLabel {
            color: #00ffff;
            font-size: 18px;
            font-weight: bold;
            padding: 20px;
            background-color: #000000;
            border: none;
        }
        QMessageBox QPushButton {
            background-color: #00ffff;
            color: #000000;
            border: 2px solid #ffffff;
            border-radius: 8px;
            padding: 10px 20px;
            font-weight: bold;
            font-size: 14px;
            min-width: 100px;
            min-height: 35px;
        }
        QMessageBox QPushButton:hover {
            background-color: #ffffff;
            color: #000000;
            border: 2px solid #00ffff;
        }
        QMessageBox QPushButton:pressed {
            background-color: #cccccc;
            color: #000000;
        }
    """)

    # 创建主窗口
    window = MainWindow()
    window.show()

    sys.exit(app.exec_())


if __name__ == "__main__":
    main()
